#ifndef __SIMPLE_THREAD_H__
#define __SIMPLE_THREAD_H__

#include <thread>
#include <sys/prctl.h>
#include <iostream>
#include <atomic>

class SimpleThread
{
public:
	SimpleThread()
		: stop_(true)
		, thread_impl_(NULL)
	{
	}
	virtual ~SimpleThread() 
	{
		stop_ = true;
		// cannot join now
		// this->join();
		delete thread_impl_;
		thread_impl_ = NULL;
	}

	int start()
	{
		// already running
		if (!stop_ && thread_impl_ != NULL) return 0;		
		stop_ = false;
		thread_impl_ = new std::thread(&SimpleThread::run, this);
		
		return 0;
	}
	
	void stop() { this->do_stop(); }

	void join() { if ((thread_impl_ != NULL) && thread_impl_->joinable()) thread_impl_->join();}

	bool is_stopped() { return stop_; }

   	void set_name(const std::string& name) { if (!name.empty()) prctl(PR_SET_NAME, name.c_str()); }

protected:
	virtual void do_run() {};
	virtual void do_stop() { stop_ = true; }

private:
	void run() { stop_ = false; this->do_run(); stop_ = true; }

protected:
	std::atomic<bool>				stop_;

private:
	std::thread*		            thread_impl_;
};


#endif // __SIMPLE_THREAD_H__
